<template>
  <div id="client">
   <p style="margin-left: 20px">
      客户：
      <el-input
        style="width: 200px; margin-left: 0px; margin-right: 20px"
        placeholder="请输入客户编号"
        v-model="saleOrder.clientName"
        clearable
      >
      </el-input>
      <el-button
        style="margin-left: -20px; margin-right: 10px"
        @click="dialogFormVisible3 = true"
        >...</el-button
      >
      &nbsp;&nbsp;&nbsp; 销售人员
      <el-select
        v-model="saleOrder.saler"
        placeholder="销售人员"
        style="width: 100px"
      >
        <el-option
          v-for="item in salemen"
          :key="item.employeeId"
          :label="item.employeeName"
          :value="item.employeeCode"
        >
        </el-option> </el-select
      >&nbsp;&nbsp;&nbsp;
      <span class="documentDate">单据日期：</span>
      <el-date-picker
        v-model="saleOrder.orderDate"
        type="datetime"
        placeholder="选择日期时间"
       value-format="yyyy-MM-dd HH:mm:ss"
      >
      </el-date-picker
      >&nbsp;&nbsp;&nbsp; 
    </p>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px; margin-right: 20px; float: right">
      <el-button  @click="save()" type="primary" v-if="isok">保存</el-button>&nbsp;&nbsp;&nbsp;
      <el-button  @click="put()" type="primary" v-if="taskId != '' "  >审核</el-button>&nbsp;&nbsp;&nbsp;
      <el-button type="success" @click="verse()" v-if="isVerse">提交</el-button>&nbsp;&nbsp;&nbsp;
      <el-button  v-if="isRe">反审核</el-button>&nbsp;&nbsp;&nbsp;
      <el-button type="primary">批量导入</el-button>&nbsp;&nbsp;&nbsp;
    </div>
    <div style="margin-top: 30px">
      <el-table
        height="250px"
        :data="tableData"
        border
        style="width: 100%; font-size: 13px"
      >
       <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeRow(scope.$index)"
              >删除</el-button
            >
            <el-button size="mini" @click="addRow">添加</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="goodcode" label="商品" width="230">
          <template slot-scope="scope">
          <el-input
            style="width: 120px; margin-left: 10px; margin-right: 20px"
            placeholder="请输入商品"
            v-model="scope.row.goodcode"
            clearable
          ></el-input>
          <el-button
            style="margin-left: -20px; margin-right: 10px; width: 50px"
            @click="goodsShow = true"
            >...</el-button
          >
          </template>
        </el-table-column>
        <el-table-column prop="goodname" label="商品名称" width="120">
        </el-table-column>
        <el-table-column prop="imagename" label="图片" width="120">
        </el-table-column>
        <el-table-column prop="unitname" label="基本单位" width="120">
        </el-table-column>
        <el-table-column prop="totalNum" label="基本数量" width="120">
         <template slot-scope="scope">
            <el-input
              v-model="scope.row.totalNum"
              placeholder="请输入"
              @input="calculateTotalPrice(scope.$index)"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="stockId" label="仓库" width="120">
          <template slot-scope="scope">
          <el-select v-model="scope.row.stockId" placeholder="请选择仓库" @change="handleStoreChange(scope.row)">
            <el-option
              v-for="item in storeList"
              :key="item.shId"
              :label="item.storeHomeName"
              :value="item.shId">
            </el-option>
          </el-select>
        </template>
        </el-table-column>
        <el-table-column prop="unitCost" label="单价" width="120">
        </el-table-column>
   <el-table-column prop="discount" label="折扣率%" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.discount"
              placeholder="请输入折扣率"
              @input="calculateTotalPrice(scope.$index)"
            >
              clearable ></el-input
            >
          </template>
        </el-table-column>
        <el-table-column prop="tax" label="税率%" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.tax"
              placeholder="请输入税率"
              @input="calculateTotalPrice(scope.$index)"
              >c clearable ></el-input
            >
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="折后含税单价" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.totalPrice"
              placeholder="请输入折后含税单价"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入备注"
              clearable
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div style="width: 100%; background-color: blanchedalmond; height: 30px">
        <table style="width: 78.7%; height: 30px">
          <tr>
            <td style="width: 50%">合计：</td>
            <td style="width: 50%">123</td>
          </tr>
        </table>
      </div> -->
      <el-input
        type="textarea"
        :rows="2"
        placeholder="暂无备注信息"
        v-model="saleOrder.remark"
        style="width: 100%; line-height: 20px"
      >
      </el-input>
      <p style="margin-top: 20px; margin-left: 20px">
    
       
        &nbsp;&nbsp; 优惠后金额：
        <el-input
          style="width: 240px; margin-left: 10px; margin-right: 20px"
          placeholder="优惠后金额："
          v-model="saleOrder.allPrice"
          clearable
        >
        </el-input
        >
      </p>
      <p style="margin-top: 20px; margin-left: 20px">
        收款条件：
        <el-select v-model="saleOrder.reinId" placeholder="收款条件" style="width: 100px">
          <el-option
            v-for="item in accounts"
            :key="item.accountCode"
            :label="item.aTypeName"
            :value="item.accountCode"
          >
          </el-option> </el-select
        >&nbsp;&nbsp;
        <span style="display: inline-block; float: right">
          <el-button @click="goto('SaleOrdersList')">历史单据</el-button
          >&nbsp;&nbsp; <el-button>操作日志</el-button></span
        >
      </p>
    </div>

    <el-dialog top="20px" title="选择客户" :visible.sync="dialogFormVisible3">
      <ClientChoose
        ref="customerCode"
        :dialogFormVisible3="dialogFormVisible3"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="yesCustomer">确 定</el-button>
      </div>
    </el-dialog>
    
    <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
      <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsShow = false">取 消</el-button>
        <el-button type="primary" @click="yesGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";
import ClientChoose from "../public_com/ClientChoose.vue";
export default {
  name: "SaleOrders",
  components: {
 GoodsChoose,
 ClientChoose,
  },
  data() {
    return {
      isRe:false,
      isok:'false',
      storeList:[],
      salemen: [],
       accounts: [],
        goodsShow: false,
      saleOrder: {
        clientName:'',
        orderNum:'',
        orderDate:'',
        documentNum:'',
        saler:'',
        customerNum:'',
        remark:'',
        dnum:'',
        allPrice:'',
      },
      document:'',
      documentNum:'',
        tableData: [          
        {
          gid:'',
          goodcode:'',
          type: 2,
          goodname: "",
          unitname: "",
          unitId: "",
          stockId: "",
          totalNum: "",
          totalPrice: "",
          tax: "",
          discount: "",
          unitCost: "",
          did: "",
        },
      ],
      id:'',
      taskId:'',
      isVerse:false,
      dialogFormVisible3: false,
      dialogFormVisible1: false,
      input: "",
      value2: "",
      value3: "",
      dialogFormVisible: false,
    };
  },
    created(){
      this.getStoreList()
       this.getSaler();
    this.getAccounts();
     var id = this.$route.query.id;
     this.taskId=this.$route.query.taskId
    alert(id)
    if (typeof id === "undefined") {
      this.id = "";
     
    } else {
    
      this.id = id;
      this.getSaleOrders(this.id);
      this.getbydid(this.id);
    }
    },
  methods: {
    getStoreList() {
      this.axios.get('/info/storeHouse/getAllStore',
        {
          params: {
            cId: 1
          }
        }
      ).then(rs => {
        this.storeList = rs.data.storeList
      })
    },
    addRow() {
      this.tableData.push({
        gid: "",
        type: 2,
        goodcode:'',
        goodname: "",
        unitname: "",
        unitid: "",
        stockId: "",
        totalNum: 0,
        totalPrice: 0,
        tax: 0,
        discount: 0,
        unitCost: "",
        did: "",
      });
    },
  getSaleOrders(id){
  
     this.axios
    ({
      url:'/sale/saleOrder/getOne',
      params:{
        orderId:this.id
      }
    }).then(rs=>{
      this.saleOrder=rs.data.isGet
      console.log(rs.data.isGet)
    })
  },
     getbydid(did) {
      this.axios({
        url: "/sale/saleOrderDetail/byDid",
        params: {
          did:this.id
        },
      }).then((rs) => {
        this.tableData = rs.data.deList;
        console.log(rs.data.deList)
      });
    },
  getSaler() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.salemen = rs.data.list;
        console.log("销货订单","salemen", rs.data);
      });
    },

       getUnitList() {
      this.axios.get("/erp/goods/basicUnit/getList").then((rs) => {
        this.unitList = rs.data.list;
        this.pageInfo.list.forEach((goods, index) => {
          // console.log(this.unitList)
          this.unitList.forEach((unit, index) => {
            if (goods.unitid == unit.id) {
              this.$set(goods, "unitname", unit.unidname);
            }
          });
        });
      });
    },
    verse(){
      this.saleOrder.documentNum=this.documentNum
        this.axios({
        url:'/sale/saleOrder/verse',
        data:{
          ...this.saleOrder
        },
        method:'post'
        }).then(rs=>{
          alert(rs.data.status)
          if(rs.data.status==true){
            this.isRe=true;
            this.isVerse=false;
          }
        })
    },
     getAccounts: function () {
      this.axios({
        url: "/info/account/selectAll",
      }).then((rs) => {
        this.accounts = rs.data.accounts;
        console.log(this.accounts);
      });
    },
     calculateTotalPrice(index) {
      var price = 0;
      const row = this.tableData[index];
      row.totalPrice =
        row.totalNum *
        (1 - row.tax / 100) *
        (1 - row.discount / 100) *
        row.unitCost;
      this.tableData.forEach((item) => {
        price = price + item.totalPrice;
      });
      this.saleOrder.allPrice = price;
    },
  
    removeRow(index) {
      this.tableData.splice(index, 1);
    },
      yesCustomer() {
      this.dialogFormVisible3 = false;
      this.saleOrder.customerNum = this.$refs.customerCode.clientCode;
      this.saleOrder.clientName = this.$refs.customerCode.clientName;
    },
  yesGoods() {
      this.goodsShow = false;
      // this.goodsList =
      // console.log(this.goodsList)
      //遍历商品列表
      this.inBoundList = this.$refs.chooseGoods.selectionList;
      console.log(this.inBoundList);
      const did = this.id;
      this.inBoundList.forEach((item) => {
        this.tableData.push({
          gid: item.gid,
          goodcode:item.goodcode,
          type: 1,
          goodname: item.goodname,
          unitname: item.unitname,
          unitId: item.unitId,
          stockId: item.stockId,
          totalNum: 0,
          totalPrice: 0,
          tax: 0,
          discount: 0,
          unitCost: item.unitCost,
          did: did,
        });
        var index1 = [];
        this.tableData.forEach((detail, index) => {
          if (detail.gid == "") {
            index1.push(index);
            console.log(index);
          }
        });
        index1.reverse().forEach((index, i) => {
          this.tableData.splice(index, 1);
        });
        console.log("tableData", this.tableData);
      });
    },
    goto(to) {
      this.$router.push(to);
    },
    save(){
      
        if(this.id!==''){
          this.saleOrder.orderId=this.id
          this.tableData.forEach(item => {
      item.did = this.id;
    });
    console.log( this.tableData)
          this.axios({
            url:'/sale/saleOrder/update',
            data:{
            saleOrder:this.saleOrder,
           tableData: this.tableData
        },
        method:'post',
          }).then(rs=>{
            alert(rs.data.status)
          })
        }else{
          this.axios({
    url:'/sale/saleOrder/add',
        data:{
            saleOrder:this.saleOrder,
           tableData: this.tableData
        },
        method:'post',
      }).then(rs=>{
        console.log(rs)
        if(rs.data.status==true){
          alert("增加成功")
          this.isok=false;
          this.documentNum=rs.data.documentNum
          this.isVerse=true
          alert(this.documentNum)
        }else{
          alert("增加失败")
        }
      
      })
        }
    
    }
  },
};
</script>

<style scoped>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

tr {
  border: 1px solid black;
}
</style>